package com.beau.service.impl;

import com.beau.common.pojo.Code;
import com.beau.dao.CodeDao;
import com.beau.service.CodeService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Random;

@Service
public class CodeServiceImpl implements CodeService{

    private final Logger logger = LoggerFactory.getLogger(CodeService.class);

    @Autowired
    private CodeDao codeDao;

    @Override
    public String genCode() {
        Random random = new Random();
        int code = random.nextInt(999999);
        while (code < 100000) {
            code = random.nextInt(999999);
        }
        logger.info("generate code " + code);
        return String.valueOf(code);
    }

    @Override
    public Code saveCode(String code, String email, Date createTime, Date expireTime) {
        Code codeEntry = new Code();
        codeEntry.setCode(code);
        codeEntry.setEmail(email);
        codeEntry.setCreatetime(createTime);
        codeEntry.setExpiretime(expireTime);
        return codeDao.save(codeEntry);
    }

    @Override
    public Integer validateCode(String email, String code) {
        Code codeEntry = codeDao.findByEmailAndCode(email, code);
        // 没有找到，说明验证码错误
        if (codeEntry == null) {
            return 1;
        }
        // 验证码超时
        if (codeEntry.getExpiretime().getTime() < System.currentTimeMillis()) {
            return 2;
        }
        return 0;
    }


}
